import sys
import json
import logging
from dotenv import load_dotenv
from openai import OpenAI
import os

# u914du7f6eu65e5u5fd7
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("python_api.log", encoding="utf-8"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

# u52a0u8f7du73afu5883u53d8u91cf
load_dotenv()

# u83b7u53d6APIu5bc6u94a5
DEEPSEEK_API_KEY = os.getenv('DEEPSEEK_API_KEY')
DEEPSEEK_API_URL = os.getenv('DEEPSEEK_API_URL', 'https://api.deepseek.com/v1')

def call_reasoner_api(input_data):
    """u8c03u7528DeepSeek Reasoner API
    
    Args:
        input_data (dict): u5305u542bu6a21u578bu3001u6d88u606fu548cu5176u4ed6u53c2u6570u7684u5b57u5178
    """
    try:
        model = input_data.get('model', 'deepseek')
        messages = input_data.get('messages', [])
        temperature = input_data.get('temperature', 0.7)
        max_tokens = input_data.get('max_tokens', 2048)
        
        logger.info(f"u5f00u59cbu4f7fu7528{model}u6a21u578bu8c03u7528API")
        
        # u68c0u67e5APIu5bc6u94a5
        if not DEEPSEEK_API_KEY or DEEPSEEK_API_KEY == 'your_deepseek_key_here':
            logger.warning("u672au8bbeu7f6eDeepSeek APIu5bc6u94a5uff0cu4f7fu7528u6a21u62dfu54cdu5e94")
            return simulate_response(messages)
        
        # u521bu5efaOpenAIu5ba2u6237u7aef
        client = OpenAI(
            api_key=DEEPSEEK_API_KEY,
            base_url=DEEPSEEK_API_URL
        )
        
        # u8c03u7528API
        response = client.chat.completions.create(
            model="deepseek-reasoner",
            messages=messages,
            stream=True,
            max_tokens=max_tokens
        )
        
        # u6d41u5f0fu8f93u51fau7ed3u679c
        for chunk in response:
            # u68c0u67e5u662fu5426u6709u601du7ef4u94feu5185u5bb9
            if hasattr(chunk.choices[0].delta, 'reasoning_content') and chunk.choices[0].delta.reasoning_content:
                content = chunk.choices[0].delta.reasoning_content
                sys.stdout.write(content)
                sys.stdout.flush()
            # u68c0u67e5u662fu5426u6709u6700u7ec8u56deu7b54
            elif hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content:
                content = chunk.choices[0].delta.content
                sys.stdout.write(content)
                sys.stdout.flush()
        
        logger.info("u6210u529fu5b8cu6210APIu8c03u7528")
    except Exception as e:
        logger.error(f"u8c03u7528APIu65f6u51fau9519: {str(e)}")
        # u51fau9519u65f6u8fd4u56deu6a21u62dfu54cdu5e94
        return simulate_response(messages)

def simulate_response(messages):
    """u751fu6210u6a21u62dfu7684u54cdu5e94"""
    user_message = messages[-1]['content'] if messages and messages[-1]['role'] == 'user' else ''
    
    # u6a21u62dfu601du7ef4u94feu8fc7u7a0b
    thinking_parts = [
        f"u5bf9u4e8eu95eeu9898 '{user_message}'\n",
        "u6211u9700u8981u8fdbu884cu601du8003\n\n",
        "u9996u5148uff0cu6211u8981u7406u89e3u95eeu9898u7684u5185u5bb9u548cu8981u6c42\n",
        "u8fd9u4e2au95eeu9898u7684u5173u952eu662f...\n",
        "u6839u636eu6211u7684u77e5u8bc6uff0cu6211u8ba4u4e3a...\n",
        "u7ecfu8fc7u5206u6790uff0cu6211u5f97u51fau4ee5u4e0bu7ed3u8bba\n"
    ]
    
    # u6a21u62dfu6700u7ec8u56deu7b54
    response_parts = [
        "u60a8u597duff01",
        f"u5173u4e8eu60a8u63d0u51fau7684'{user_message}'u7684u95eeu9898uff0c",
        "u6211u7684u56deu7b54u662fuff1a\n",
        "u2026u2026u8fd9u91ccu662fu8be6u7ec6u89e3u91cau2026u2026\n",
        "u5e0cu671bu6211u7684u56deu7b54u5bf9u60a8u6709u6240u5e2eu52a9uff01u5982u679cu8fd8u6709u5176u4ed6u95eeu9898uff0cu8bf7u968fu65f6u63d0u95eeu3002"
    ]
    
    # u6a21u62dfu601du7ef4u94feu8f93u51fa
    for part in thinking_parts:
        sys.stdout.write(part)
        sys.stdout.flush()
        # u6a21u62dfu4e00u4e9bu5ef6u8fdf
        # time.sleep(0.5)
    
    # u6a21u62dfu6700u7ec8u56deu7b54u8f93u51fa
    for part in response_parts:
        sys.stdout.write(part)
        sys.stdout.flush()
        # u6a21u62dfu4e00u4e9bu5ef6u8fdf
        # time.sleep(0.5)

def main():
    """u4e3bu51fdu6570uff0cu5904u7406u547du4ee4u884cu53c2u6570u5e76u8c03u7528API"""
    try:
        if len(sys.argv) < 2:
            logger.error("u7f3au5c11u8f93u5165u6587u4ef6u8defu5f84u53c2u6570")
            sys.exit(1)
        
        input_file = sys.argv[1]
        
        # u68c0u67e5u6587u4ef6u662fu5426u5b58u5728
        if not os.path.exists(input_file):
            logger.error(f"u6307u5b9au7684u6587u4ef6u4e0du5b58u5728: {input_file}")
            sys.exit(1)
        
        # u8bfbu53d6u548cu89e3u6790u5165u53c3u6570
        with open(input_file, 'r', encoding='utf-8') as f:
            input_data = json.load(f)
        
        # u8c03u7528API
        call_reasoner_api(input_data)
    except Exception as e:
        logger.error(f"u6267u884cu811au672cu65f6u51fau9519: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    main()
